package com.yl.applicationsecurity.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yl.applicationsecurity.mapper.NationMapper;
import com.yl.applicationsecurity.mapper.ScriptStateMapper;
import com.yl.applicationsecurity.mapper.SgmSafeRiskItemMapper;
import com.yl.applicationsecurity.mapper.SgmSafeRiskMapper;
import com.yl.applicationsecurity.pojo.*;
import com.yl.applicationsecurity.service.NationService;
import com.yl.applicationsecurity.service.SgmSafeRiskService;
import com.yl.applicationsecurity.utils.Constant;
import com.yl.applicationsecurity.utils.StrictHolidayCalculatorUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

/**
 * @author 鹤仙问鹿仙
 * @program: Application-security
 * @description:
 * @date 2025-02-08 14:22:57
 */
@Service
public class SgmSafeRiskServiceImpl extends ServiceImpl<SgmSafeRiskMapper, SgmSafeRisk> implements SgmSafeRiskService {
    @Autowired
    private ScriptStateMapper scriptStateMapper;
    @Autowired
    private SgmSafeRiskItemMapper   sgmSafeRiskItemMapper;

    private static final Logger logger = Logger.getLogger("SgmSafeRiskServiceImpl");


    @Override
    public PageInfo<SgmSafeRisk> findListBySgmSafeRisk(String[] nationSelect, String[] systemNameSelect, SgmSafeRisk sgmSafeRisk, Date startFirstDate, Date endFirstDate, Integer pageNum
            , Integer pageSize,Integer[] excessiveTypeArray,Integer[] statusArray ){


        PageHelper.startPage(pageNum, pageSize );//每页显示8条

        LambdaQueryWrapper<SgmSafeRisk> lambdaQueryWrapper = new LambdaQueryWrapper<>();


        //根据URL模糊查询
        if ( StringUtils.isNotEmpty(sgmSafeRisk.getUrl())){
            lambdaQueryWrapper.like(SgmSafeRisk::getUrl,sgmSafeRisk.getUrl());
        }

        //根据菜单模糊查询
        if ( StringUtils.isNotEmpty(sgmSafeRisk.getMenu())){
            lambdaQueryWrapper.like(SgmSafeRisk::getMenu,sgmSafeRisk.getMenu());
        }


        //根据漏洞类型查询
        if ( excessiveTypeArray!=null&&excessiveTypeArray.length!=0){
            lambdaQueryWrapper.in(SgmSafeRisk::getExcessiveType,excessiveTypeArray);
        }

        //根据漏洞状态查询
        if ( statusArray!=null&&statusArray.length!=0){
            lambdaQueryWrapper.in(SgmSafeRisk::getStatus,statusArray);
        }

        // 根据漏洞所属系统多选查询
        if (null!=systemNameSelect&&systemNameSelect.length!=0){
            lambdaQueryWrapper.in(SgmSafeRisk::getSystemName,systemNameSelect);
        }


        //按照国家多选查询

        if (null!=nationSelect&&nationSelect.length!=0){
            lambdaQueryWrapper.in(SgmSafeRisk::getCountry,nationSelect);
        }


        //根据首次发现时间查询
        if(startFirstDate!=null){
            lambdaQueryWrapper.ge(SgmSafeRisk::getFirstTime, startFirstDate);
        }

        if(endFirstDate!=null){
            lambdaQueryWrapper.le(SgmSafeRisk::getFirstTime, endFirstDate);
        }

        //根据AI审计结果
        if ( sgmSafeRisk.getAiCheck()!=null){
            lambdaQueryWrapper.eq(SgmSafeRisk::getAiCheck,sgmSafeRisk.getAiCheck());
        }

        lambdaQueryWrapper.orderByDesc(SgmSafeRisk::getFirstTime);//根据首次发现时间排序
        List<SgmSafeRisk> list = baseMapper.selectList(lambdaQueryWrapper);

        PageInfo<SgmSafeRisk> pageInfo = new PageInfo<SgmSafeRisk>(list);

        if (pageInfo.getPages() == 0) {
            pageInfo.setPages(1);
        }

        return pageInfo;
    }

    @Override
    public SgmSafeRisk findOneById(Long safeRiskId) {
        return baseMapper.selectById(safeRiskId);
    }

    @Override
    public int updateStatus(String[] ids, Integer updateStatus) {
        if(ids==null||ids.length==0){
            return 1;
        }
        LambdaUpdateWrapper<SgmSafeRisk> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(SgmSafeRisk::getStatus,updateStatus);
        lambdaUpdateWrapper.set(SgmSafeRisk::getLastDisposalDate,new Date());
        lambdaUpdateWrapper.in(SgmSafeRisk::getId , ids);
        return baseMapper.update(null,lambdaUpdateWrapper);
    }

    @Override
    public int add(String url, String systemName, Integer excessiveType, String level, String country, String request, String response,Date createDate,String menu,Integer aicheck) {



        // 先查询 SgmSafeRisk 是否已经存在值，如果存在执行修改操作，修改最近一次发现时间，如果不存在则执行插入操作 （判断依据：url systemName  level country）
        LambdaQueryWrapper<SgmSafeRisk> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if ( StringUtils.isNotEmpty(url)){
            lambdaQueryWrapper.eq(SgmSafeRisk::getUrl,url.trim());
        }

        if ( StringUtils.isNotEmpty(systemName)){
            lambdaQueryWrapper.eq(SgmSafeRisk::getSystemName,systemName.trim());
        }

        if ( StringUtils.isNotEmpty(level)){
            lambdaQueryWrapper.eq(SgmSafeRisk::getLevel,level.trim());
        }

        if ( StringUtils.isNotEmpty(country)){
            lambdaQueryWrapper.eq(SgmSafeRisk::getCountry,country.trim());
        }
        if (excessiveType!=null){
            lambdaQueryWrapper.eq(SgmSafeRisk::getExcessiveType,excessiveType);
        }



        SgmSafeRisk sgmSafeRisk = baseMapper.selectOne(lambdaQueryWrapper);


        //为避免重复插入，需先校验当前记录是否重复，根据url、应用、层级、国家、发现时间 来判断
        if (createDate!=null){
            lambdaQueryWrapper.eq(SgmSafeRisk::getLastTime,createDate);
        }
        if(baseMapper.selectOne(lambdaQueryWrapper)!=null){
            //如果数据存在，则拒绝
            return 0;
        }


        if(sgmSafeRisk==null){
            sgmSafeRisk = new SgmSafeRisk();
            sgmSafeRisk.setId( System.currentTimeMillis());
            sgmSafeRisk.setCountry(country.trim());
            sgmSafeRisk.setLevel(level.trim());
            sgmSafeRisk.setFirstTime(createDate);
            sgmSafeRisk.setLastTime(createDate);
            sgmSafeRisk.setExcessiveType(excessiveType);
            sgmSafeRisk.setSystemName(systemName.trim());
            sgmSafeRisk.setUrl(url.trim());
            sgmSafeRisk.setStatus(0);
            sgmSafeRisk.setVulnerLevel("P2");
            sgmSafeRisk.setMenu(menu);
            sgmSafeRisk.setAiCheck(aicheck);
            sgmSafeRisk.setLastSystemProcessingDate(new Date());

            //7个工作日需要修复.计算出超期时间
            LocalDateTime localDateTime = StrictHolidayCalculatorUtil.calculateTargetDate(LocalDateTime.now(), Constant.P2_TIMELINESS);
            sgmSafeRisk.setOverdueDate(Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()));
            sgmSafeRisk.setUpdateTime(new Date());
            baseMapper.insert(sgmSafeRisk);
        }else{

            LambdaUpdateWrapper<SgmSafeRisk> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            Date lastDisposalDate = sgmSafeRisk.getLastDisposalDate();
            LocalDateTime disposalPlus7Days = null;
            if(lastDisposalDate!=null){
                disposalPlus7Days = lastDisposalDate.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime()
                        .plusDays(7);
            }

            //如果当前告警的状态是暂无数据、已修复（且当前时间大于 上次与人工审计的时间+7天），则更新成待处理
            if (sgmSafeRisk.getStatus()==7||(sgmSafeRisk.getStatus()==4&&disposalPlus7Days!=null&&disposalPlus7Days.isBefore(LocalDateTime.now()))){
                lambdaUpdateWrapper.set(SgmSafeRisk::getStatus,0);
                //5个工作日需要修复.计算出超期时间
                LocalDateTime localDateTime = StrictHolidayCalculatorUtil.calculateTargetDate(LocalDateTime.now(), Constant.P2_TIMELINESS);
                lambdaUpdateWrapper.set(SgmSafeRisk::getOverdueDate,Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()));
                lambdaUpdateWrapper.set(SgmSafeRisk::getUpdateTime,new Date());//
                lambdaUpdateWrapper.set(SgmSafeRisk::getLastSystemProcessingDate,new Date());
            }
            lambdaUpdateWrapper.set(SgmSafeRisk::getAiCheck,aicheck);//ai审核结果
            lambdaUpdateWrapper.set(SgmSafeRisk::getMenu,menu);
            lambdaUpdateWrapper.set(SgmSafeRisk::getLastTime,createDate).in(SgmSafeRisk::getId , sgmSafeRisk.getId());
            baseMapper.update(null,lambdaUpdateWrapper);
        }
        //插入sgmSafeRiskItem数据
        SgmSafeRiskItem sgmSafeRiskItem = new SgmSafeRiskItem();
        sgmSafeRiskItem.setId( System.currentTimeMillis());
        sgmSafeRiskItem.setSafeRiskId(sgmSafeRisk.getId());
        sgmSafeRiskItem.setQueryString(request);
        sgmSafeRiskItem.setResponse(response);
        sgmSafeRiskItem.setCreateTime(createDate);
        sgmSafeRiskItem.setUpdateTime(new Date());//作为插入数据库的时间
        return sgmSafeRiskItemMapper.insert(sgmSafeRiskItem);
    }


}

